<template>
  <div class="product-list">
    <!-- 搜索和筛选区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索商品"
        prefix-icon="el-icon-search"
        clearable
        @clear="handleSearch"
        @keyup.enter.native="handleSearch"
        class="search-input"
      ></el-input>
      <el-select v-model="selectedCategory" placeholder="商品分类" clearable @change="handleSearch">
        <el-option
          v-for="item in categories"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
    </div>

    <!-- 商品列表 -->
    <el-row :gutter="20" class="product-grid">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="product in products" :key="product.id" class="product-col">
        <el-card :body-style="{ padding: '0px' }" class="product-card" shadow="hover">
          <div class="product-image">
            <img :src="getImageUrl(product.imageUrl)" :alt="product.name">
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">¥{{ product.price }}</div>
            <div class="product-stock">库存: {{ product.stock }}</div>
            <div class="product-actions">
              <el-button type="primary" size="small" @click="addToCart(product)" :disabled="product.stock <= 0">
                {{ product.stock > 0 ? '加入购物车' : '暂时缺货' }}
              </el-button>
              <el-button type="text" size="small" @click="viewDetail(product.id)">查看详情</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[12, 24, 36, 48]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 添加到购物车的对话框 -->
    <el-dialog
      title="添加到购物车"
      :visible.sync="dialogVisible"
      width="30%">
      <div class="quantity-selector">
        <span>数量：</span>
        <el-input-number
          v-model="quantity"
          :min="1"
          :max="selectedProduct ? selectedProduct.stock : 1"
          size="small">
        </el-input-number>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddToCart">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getProductList } from '@/api/product'
import { mapActions } from 'vuex'

export default {
  name: 'ProductList',
  data() {
    return {
      searchQuery: '',
      selectedCategory: '',
      products: [],
      currentPage: 1,
      pageSize: 12,
      total: 0,
      categories: [
        { value: '食品', label: '宠物食品' },
        { value: '玩具', label: '玩具用品' },
        { value: '用品', label: '日用品' },
        { value: '护理', label: '护理用品' }
      ],
      dialogVisible: false,
      quantity: 1,
      selectedProduct: null
    }
  },
  created() {
    this.fetchProducts()
  },
  methods: {
    ...mapActions('cart', ['addProductToCart']),
    
    async fetchProducts() {
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery,
          category: this.selectedCategory
        }
        const response = await getProductList(params)
        if (response.code === 200 && response.data) {
          this.products = response.data.list || []
          this.total = response.data.total || 0
        } else {
          this.$message.error('获取商品列表失败：' + (response.message || '未知错误'))
        }
      } catch (error) {
        console.error('获取商品列表错误:', error)
        this.$message.error('获取商品列表失败：' + (error.message || '未知错误'))
      }
    },

    handleSearch() {
      this.currentPage = 1
      this.fetchProducts()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.fetchProducts()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchProducts()
    },

    addToCart(product) {
      this.selectedProduct = product
      this.quantity = 1
      this.dialogVisible = true
    },

    async confirmAddToCart() {
      try {
        await this.addProductToCart({
          productId: this.selectedProduct.id,
          quantity: this.quantity
        })
        this.$message.success('添加到购物车成功')
        this.dialogVisible = false
      } catch (error) {
        this.$message.error('添加到购物车失败')
      }
    },

    viewDetail(id) {
      this.$router.push(`/main/shop/products/${id}`)
    },

    getImageUrl(path) {
      if (!path) {
        return require('@/assets/default.jpg');
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
      }
      
      // 构建完整URL
      return serverUrl + path;
    }
  }
}
</script>

<style lang="scss" scoped>
.product-list {
  padding: 20px;

  .search-bar {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    .search-input {
      width: 300px;
    }
  }

  .product-grid {
    margin-bottom: 20px;
  }

  .product-col {
    margin-bottom: 20px;
  }

  .product-card {
    height: 100%;
    display: flex;
    flex-direction: column;

    .product-image {
      height: 200px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .product-info {
      padding: 14px;

      .product-name {
        margin: 0;
        font-size: 16px;
        color: #333;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .product-price {
        color: #f56c6c;
        font-size: 18px;
        font-weight: bold;
        margin: 10px 0;
      }

      .product-stock {
        color: #999;
        font-size: 14px;
        margin-bottom: 10px;
      }

      .product-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }

  .pagination {
    text-align: center;
    margin-top: 20px;
  }

  .quantity-selector {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
  }
}
</style> 